import { api } from '../../config/api'
import { request } from '../../utils/request'
const app = getApp()
Page({
	data: {
		//1=微信授权登陆;2=账号密码登陆
		loginType: 1,
		formData: {
			account: '',
			password: ''
		},
		showPassword: false,
		loading: false
	},
	changEye: function () {
		this.setData({
			showPassword: !this.data.showPassword
		})
	},
	inputChange: function (e) {
		let prop = e.currentTarget.dataset.prop
		let value = e.detail.value
		this.data.formData[prop] = value
		this.setData({
			formData: this.data.formData
		})
	},
	login: function (res) {
		const { account, password } = this.data.formData
		const me = this
		me.setData({ loading: true })
		request.post(api.user.login, { mobile: account, password })
			.then(res => {
				me.setData({ loading: false })
				app.globalData.isLogin = true
				wx.setStorageSync('token', res.access_token)
				wx.navigateBack({})
			}).catch((res) => {
				me.setData({ loading: false });
				wx.showToast({
					title: '登陆失败',
					icon: "none",
					duration: 2000
				});
			});
	},
	loginByWx() {
		wx.showModal({
			title: '温馨提示',
			content: '亲，确认授权微信登录吗？',
			success(res) {
				//如果用户点击了确定按钮
				if (res.confirm) {
					wx.getUserProfile({
						desc: '获取你的昵称、头像、地区及性别',
						success: profile => {
							wx.login({
								success: (res) => {
									if (res.code) {
										wx.showLoading({ title: '请稍后' });
										const loginData = { ...profile.userInfo, code: res.code };
										request.post(api.user.loginByWx, loginData)
											.then(loginRes => {
												app.globalData.isLogin = true;
												wx.setStorageSync('token', loginRes.access_token);
												wx.navigateBack({});
											});
									}
								},
							})
						},
						fail: res => {
							//拒绝授权
							wx.showToast({
								title: '授权失败',
								icon: 'none',
								duration: 2000
							});
							return;
						}
					});
				} else if (res.cancel) {
					//如果用户点击了取消按钮
					wx.showToast({
						title: '您拒绝了授权，请使用其它方式登陆',
						icon: 'none',
						duration: 2000
					});
					return;
				}
			}
		})
	},
	changeToPassword() {
		this.setData({ loginType: 2 });
	},
	changeToWeixin() {
		this.setData({ loginType: 1 });
	},
	onShow() {
		wx.setNavigationBarColor({
			frontColor: '#ffffff',
			backgroundColor: '#09c475',
			animation: {
				duration: 400,
				timingFunc: 'easeIn'
			},
			success: () => {
				console.log('导航栏背景颜色设置成功')
			},
			fail: () => {
				console.log('导航栏背景颜色设置失败')
			},
			complete: () => {
				console.log('导航栏背景颜色设置结束')
			},
		})
	},
})